# -*- coding: utf-8 -*-
"""
GraphRAG API端点 - 基于LangChain实现
"""
import logging
from fastapi import APIRouter
from schemas.response import Response
from schemas.graph_rag import (
    GraphRAGRequest,
    GraphRAGResponse,
    GraphStatsResponse,
    HealthCheckResponse
)

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/graph")


@router.post("/rag", response_model=Response, summary="GraphRAG智能查询")
async def graph_rag_query(request: GraphRAGRequest):
    """
    GraphRAG智能查询 - 基于LangChain + 阿里云百炼Qwen
    
    **核心能力**:
    - 🧠 自然语言理解：直接用中文提问
    - 🔍 自动生成Cypher：LLM自动翻译为图查询
    - 📊 智能数据分析：基于图谱数据生成专业分析
    - 📝 Markdown格式输出：结构化、可读性强
    
    **示例问题**:
    
    1. **趋势分析**:
       - "海豹车型在2022年到2024年的销量趋势是什么？"
       - "分析特斯拉Model Y在2023年的市场表现"
    
    2. **对比分析**:
       - "对比比亚迪和特斯拉在2023年的销量"
       - "新能源车和传统燃油车的销量差异"
    
    3. **聚合统计**:
       - "统计各国品牌的市场份额"
       - "2023年销量前10的车型有哪些？"
    
    4. **关系查询**:
       - "海豹是哪个品牌的车型？"
       - "比亚迪旗下有哪些新能源车型？"
    
    **响应格式**:
    ```json
    {
        "code": 200,
        "message": "查询成功",
        "data": {
            "answer": "## 海豹车型销量趋势分析...",
            "cypher": "MATCH (car:CarModel {name: '海豹'})...",
            "context": [...],
            "metadata": {...}
        }
    }
    ```
    
    **特点**:
    - ✅ 无需预定义查询模式
    - ✅ 自动识别实体和时间范围
    - ✅ 智能数据可视化建议
    - ✅ 专业级分析报告
    """
    try:
        from services.langchain_graphrag_service import LangChainGraphRAGService
        
        # 创建服务实例
        service = LangChainGraphRAGService()
        
        # 执行查询
        result = await service.query(
            question=request.question,
            return_cypher=request.return_cypher,
            return_context=request.return_context
        )
        
        # 检查是否有错误
        if result.get("error"):
            return Response.fail(
                message=f"查询失败: {result['error']}",
                data=result
            )
        
        # 构建响应
        response_data = GraphRAGResponse(**result)
        
        return Response.success(
            data=response_data.dict(),
            message="GraphRAG查询成功"
        )
        
    except Exception as e:
        logger.error(f"GraphRAG查询失败: {e}")
        import traceback
        traceback.print_exc()
        return Response.fail(message=f"查询失败: {str(e)}")


@router.get("/stats", response_model=Response, summary="获取图谱统计信息")
async def get_graph_stats():
    """
    获取Neo4j知识图谱的统计信息
    
    **返回内容**:
    - 总节点数
    - 总关系数
    - 各类型节点数量分布
    - 各类型关系数量分布
    - 图谱Schema
    
    **示例响应**:
    ```json
    {
        "total_nodes": 40000,
        "total_relationships": 120000,
        "node_statistics": {
            "CarModel": 1321,
            "SalesRecord": 38806,
            "Brand": 215,
            "Manufacturer": 45,
            "Country": 12,
            "BodyType": 8
        },
        "relationship_statistics": {
            "HAS_SALES_RECORD": 38806,
            "BELONGS_TO": 1321,
            "OWNED_BY": 215,
            "FROM_COUNTRY": 215,
            "HAS_BODY_TYPE": 1321
        }
    }
    ```
    """
    try:
        from services.langchain_graphrag_service import LangChainGraphRAGService
        
        service = LangChainGraphRAGService()
        stats = await service.get_graph_stats()
        
        if stats.get("error"):
            return Response.fail(message=f"获取统计失败: {stats['error']}")
        
        response_data = GraphStatsResponse(**stats)
        return Response.success(data=response_data.dict(), message="统计信息获取成功")
        
    except Exception as e:
        logger.error(f"获取统计信息失败: {e}")
        return Response.fail(message=f"获取失败: {str(e)}")


@router.get("/health", response_model=Response, summary="健康检查")
async def health_check():
    """
    检查Neo4j连接和LangChain服务状态
    
    **检查项**:
    - Neo4j数据库连接
    - Schema加载状态
    - 测试查询执行
    
    **示例响应**:
    ```json
    {
        "status": "connected",
        "test_result": [{"test": 1}],
        "schema_loaded": true
    }
    ```
    """
    try:
        from services.langchain_graphrag_service import LangChainGraphRAGService
        
        service = LangChainGraphRAGService()
        health = await service.test_connection()
        
        if health.get("status") == "error":
            return Response.fail(
                message=f"连接失败: {health.get('error')}",
                data=health
            )
        
        response_data = HealthCheckResponse(**health)
        return Response.success(data=response_data.dict(), message="连接正常")
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return Response.fail(message=f"检查失败: {str(e)}")
